package com.pluszg.nutrition.database.utils;

import com.pluszg.nutrition.common.bean.ApplicationHolder;
import com.pluszg.nutrition.common.utils.Assert;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

import static lombok.AccessLevel.PRIVATE;

@NoArgsConstructor(access = PRIVATE)
@Slf4j
public class TransactionUtils {

    /**
     * 开启事务
     *
     * @return
     */
    public static TransactionStatus openTransaction() {
        PlatformTransactionManager transactionManager = getManager();
        TransactionDefinition transactionDefinition = ApplicationHolder.getBean(TransactionDefinition.class);
        Assert.isTrue(ObjectUtils.allNotNull(transactionManager, transactionDefinition), "获取事务失败");
        TransactionStatus transactionStatus = transactionManager.getTransaction(transactionDefinition);
        Assert.notNull(transactionStatus, "获取事务失败");
        return transactionStatus;
    }

    /**
     * 提交事务
     *
     * @param transactionStatus
     */
    public static void commit(TransactionStatus transactionStatus) {
        getManager().commit(transactionStatus);
    }

    /**
     * 回滚事务
     *
     * @param transactionStatus
     */
    public static void rollback(TransactionStatus transactionStatus) {
        getManager().rollback(transactionStatus);
    }

    /**
     * 获取事务管理器
     *
     * @return
     */
    public static PlatformTransactionManager getManager() {
        PlatformTransactionManager manager = ApplicationHolder.getBean(PlatformTransactionManager.class);
        Assert.notNull(manager, "获取事务管理器失败");
        return manager;
    }
}
